Data visualisation


Registration number: 19BCE1717
Faculty: Prof. Pavithra R
Slot: L55 + L56
Course code: CSE3020


Part 1: Basic Datatypes in R

rm(list=ls())
#1) Assign a decimal value to a variable A and display it.
A <- 10.5
print(A)
## [1] 10.5
#2) Print the class name of the variable A.
print(class(A))
## [1] "numeric"
#3) Check whether the variable A is of type 'numeric'.
print(is.numeric(A))
## [1] TRUE
#4) Assign an integer value to a variable B and display it.
B <- 5L
print(B)
## [1] 5
#5) Check whether the variable B is of type 'integer'.
print(is.integer(B))
## [1] TRUE
#6) Create a variable C which stores the integer part of variable A.
C=as.integer(A)
print(C)
## [1] 10
#7) Compute the cost of a chocolate.
cost <- C/B
print(cost)
## [1] 2
#8) Represent the money as character string.
as.character(A)
## [1] "10.5"
#9) Store the first name and last name of the kid.
fname="Ram"
lname="kumar"
print(is.integer(fname))
## [1] FALSE
#10) Display the message "Ram bought <B> chocolates"
print(sprintf("%s bought %d chocolates", paste(fname,lname), B))
## [1] "Ram kumar bought 5 chocolates"
#11) Extract the substring "Little" from the rhymes.
rhymes="Twinkle Twinkle Little Star"
print(substr(rhymes,start=17,stop=22))
## [1] "Little"
#12) Replace "Little" as Big.
print(sub("Little", "Big", rhymes))
## [1] "Twinkle Twinkle Big Star"
#13) Assign a complex number to a variable X.
X <- 2+4i
X
## [1] 2+4i
#14) Display the real part of X.
print(Re(X))
## [1] 2
#15) Display the imaginary part of X.
print(Im(X))
## [1] 4
#16) Compute square root of a negative number
print(sqrt(as.complex(-2))) #sqrt(-2+0i) also works
## [1] 0+1.414214i
#17) Check whether real part of X is greater than its imaginary part.
chk <- Re(X)>Im(X)
print(chk)
## [1] FALSE

Part 2: Working with vectors

rm(list=ls())
#1. Create vector 'class' to store the class names 'class1','class2',.,'class5'
class=c("class1", "class2","class3","class4","class5")
print(class)
## [1] "class1" "class2" "class3" "class4" "class5"
#2. Use assign() function to create a vector 'avg' to store the average marks.
assign("avg",c(63.5,72.3,88.9,65.4,79.8))
print(avg)
## [1] 63.5 72.3 88.9 65.4 79.8
#3. Display the average mark of class2.
print(avg[2])
## [1] 72.3
#4. Combine the vectors 'class' and 'avg' as details.
details=c(class,avg)
print(details)
##  [1] "class1" "class2" "class3" "class4" "class5" "63.5"   "72.3"   "88.9"  
##  [9] "65.4"   "79.8"
#5. Find the length of combined vector 'details'.
print(length(details))
## [1] 10
#6. Find the minimum average mark and print the class which scored it.
print(min(avg))
## [1] 63.5
print(class[which.min(avg)]) #which.min(avg)returns the index of the minimum value in vector avg
## [1] "class1"
#7. Find the maximum average mark and print the class which scored it.
print(max(avg))
## [1] 88.9
print(class[which.max(avg)])
## [1] "class3"
#8. Find the total of average marks scored by all classes.
print(sum(avg))
## [1] 369.9
#9. Find the mean of the average marks scored by all classes.
print(mean(avg))
## [1] 73.98
#10. Find the standard deviation of the average marks scored by all classes.
print(sd(avg))
## [1] 10.52079
#11. Arrange the average marks in ascending order.
print(sort(avg))
## [1] 63.5 65.4 72.3 79.8 88.9
#12. Create a vector classes by repeat the vector class twice.
classes <- rep(class,times=2)
print(classes)
##  [1] "class1" "class2" "class3" "class4" "class5" "class1" "class2" "class3"
##  [9] "class4" "class5"
#13. Create a vector marks by repeating each average mark twice.
marks <- rep(avg,each=2)
print(marks)
##  [1] 63.5 63.5 72.3 72.3 88.9 88.9 65.4 65.4 79.8 79.8
#14. Create a sequence of 10 to 1. Add it to the vector avg and display it.
s=seq(10,1)
print(avg+s)
##  [1] 73.5 81.3 96.9 72.4 85.8 68.5 76.3 91.9 67.4 80.8
#15. Create a vector bool that contains logical values 'TRUE' or 'FALSE' depending on the condition average marks>70.
bool=avg>70
print(class[bool])
## [1] "class2" "class3" "class5"

Part 3: Working with matrix

rm(list=ls())
#1. Represent the height information of a team of 12 basketball players as a matrix of dimension 4x3 in row major form.
height=matrix(c(162,173,160,181,159,176,183,162,181,160,170,172),nrow=4,ncol=3,byrow=TRUE)
print(height)
##      [,1] [,2] [,3]
## [1,]  162  173  160
## [2,]  181  159  176
## [3,]  183  162  181
## [4,]  160  170  172
#2. Display the height at row 3 and column 2.
print(height[3,2])
## [1] 162
#3. Display all the heights in row 2.
print(height[2,])
## [1] 181 159 176
#Display all the heights in column 3.
print(height[,3])
## [1] 160 176 181 172
#5. Extract the heights in all rows but only in column 1 and 3.
print(height[,c(1,3)])
##      [,1] [,2]
## [1,]  162  160
## [2,]  181  176
## [3,]  183  181
## [4,]  160  172
#6. Find the transpose of the matrix.
print(t(height))
##      [,1] [,2] [,3] [,4]
## [1,]  162  181  183  160
## [2,]  173  159  162  170
## [3,]  160  176  181  172
#7. Four more players got added to the team. Update the matrix to reflect the heights of the players.
height=cbind(height,c(176,168,161,172))
print(height)
##      [,1] [,2] [,3] [,4]
## [1,]  162  173  160  176
## [2,]  181  159  176  168
## [3,]  183  162  181  161
## [4,]  160  170  172  172
#8. Append four more players' height in the matrix.
height=rbind(height,c(175,162,170,165))
print(height)
##      [,1] [,2] [,3] [,4]
## [1,]  162  173  160  176
## [2,]  181  159  176  168
## [3,]  183  162  181  161
## [4,]  160  170  172  172
## [5,]  175  162  170  165

Part 4: R commands from the PPT


Basic mathematical operations:
# Root
print(sqrt(2))
## [1] 1.414214
# Log
print(log(2))
## [1] 0.6931472
# Assignment and arithmetic (+) operation
x = 5
y = 10
z <- x + y
print(z)
## [1] 15
# floor:
floor(5.555)
## [1] 5
# round:
round(5.555)
## [1] 6
Generate a vector with common difference:
v = seq(1,5, by=.5)
v
## [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
Vector operations:
v1 = c(6,5,4,3,2,1)
v2 = c(10,9,8,7,6,5)

# Arithmetic operation on the vectors
v3 = v1 + v2
print(v3)
## [1] 16 14 12 10  8  6
vector = c(5,1,46,5,4,3,2,1)
sorted_vector <- sort(vector)

# Sort
sorted_vector
## [1]  1  1  2  3  4  5  5 46
# Rank
rank(vector)
## [1] 6.5 1.5 8.0 6.5 5.0 4.0 3.0 1.5
# Order
order(vector)
## [1] 2 8 7 6 5 1 4 3
# Which
which(vector == 16)
## integer(0)
Operations of V3 vector:
# I have also used the paste and print functions here
print("Operations of V3 vector")
## [1] "Operations of V3 vector"
print(paste("Maximum = ", max(v3)))
## [1] "Maximum =  16"
print(paste("Minimum = ", min(v3)))
## [1] "Minimum =  6"
print(paste("Mean = ", mean(v3)))
## [1] "Mean =  11"
print(paste("Standard deviation = ", sd(v3)))
## [1] "Standard deviation =  3.74165738677394"
print(paste("Length of the vector V3 = ", length(v3)))
## [1] "Length of the vector V3 =  6"
Sampler:
#Without replacement
sample(1:40, 5)
## [1] 31 36 30 10 40
#With replacement
sample(1:50, 10, replace=T)
##  [1] 14  7 36 12 22 23 24  7 18  4
R bind:
a <- c(1, 2, 3, 4, 5)
b <- c(6, 7, 8, 9, 10)
r_matrix <- rbind(a, b)
r_matrix
##   [,1] [,2] [,3] [,4] [,5]
## a    1    2    3    4    5
## b    6    7    8    9   10
C Bind:
c_matrix <- cbind(a, b)
c_matrix
##      a  b
## [1,] 1  6
## [2,] 2  7
## [3,] 3  8
## [4,] 4  9
## [5,] 5 10
Repetition to create a vector:
rep(c(1:4), 3)
##  [1] 1 2 3 4 1 2 3 4 1 2 3 4
Random number generator with levels:
gl(2, 10, length=20)
##  [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
## Levels: 1 2

Dataframe

Inbuilt: Import and load the Iris dataset from the MASS package:
library("MASS")
data(iris)
head(iris, 5)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
User generated dataframe:
students <- c("Makesh", "Anthra", "Bettina", "Chandhru", "Shyam")
event_1 <- c(10,10,6,8,10)
event_2 <- c(5,7,9,0,0)
event_3 <- c(7,9,0,8,6)
event_4 <- c(9,7,8,10,10)
data <- data.frame(students, event_1, event_2, event_3, event_4)
data
##   students event_1 event_2 event_3 event_4
## 1   Makesh      10       5       7       9
## 2   Anthra      10       7       9       7
## 3  Bettina       6       9       0       8
## 4 Chandhru       8       0       8      10
## 5    Shyam      10       0       6      10
Read from the directory:
directory_read <- read.csv("sample.csv")
## Warning in read.table(file = file, header = header, sep = sep, quote = quote, :
## incomplete final line found by readTableHeader on 'sample.csv'
head(directory_read)
##   students event_1 event_2 event_3 event_4 total_score
## 1    Kavya      10       5       7       9          31
## 2  Pushkar      10       7       9       7          33
## 3  Deepesh       6       9       0       8          23
Explore the dataset using common functions

Dimensions:

dim(iris)
## [1] 150   5

Structure:

str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

Use table() function:

table(iris$Sepal.Length)
## 
## 4.3 4.4 4.5 4.6 4.7 4.8 4.9   5 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9   6 6.1 6.2 
##   1   3   1   4   2   5   6  10   9   4   1   6   7   6   8   7   3   6   6   4 
## 6.3 6.4 6.5 6.6 6.7 6.8 6.9   7 7.1 7.2 7.3 7.4 7.6 7.7 7.9 
##   9   7   5   2   8   3   4   1   1   3   1   1   1   4   1

Names and attributes:

names(iris)
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"
attributes(iris)
## $names
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"     
## 
## $class
## [1] "data.frame"
## 
## $row.names
##   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
##  [19]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
##  [37]  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
##  [55]  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
##  [73]  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
##  [91]  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
## [109] 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## [127] 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## [145] 145 146 147 148 149 150

Tail and head (3) tuples:

head(iris, 3)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
tail(iris, 3)
##     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
## 148          6.5         3.0          5.2         2.0 virginica
## 149          6.2         3.4          5.4         2.3 virginica
## 150          5.9         3.0          5.1         1.8 virginica

Summary:

summary(iris)
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## 

Quantile:

quantile(iris$Sepal.Length)
##   0%  25%  50%  75% 100% 
##  4.3  5.1  5.8  6.4  7.9
quantile(iris$Sepal.Length, c(.1, .3, .65)) # choose the quantiles
##  10%  30%  65% 
## 4.80 5.27 6.20

Variance:

var(iris$Sepal.Length)
## [1] 0.6856935

Covariance:

cov(iris$Sepal.Length, iris$Petal.Length)
## [1] 1.274315

Covariance matrix:

cov(iris[,1:4])
##              Sepal.Length Sepal.Width Petal.Length Petal.Width
## Sepal.Length    0.6856935  -0.0424340    1.2743154   0.5162707
## Sepal.Width    -0.0424340   0.1899794   -0.3296564  -0.1216394
## Petal.Length    1.2743154  -0.3296564    3.1162779   1.2956094
## Petal.Width     0.5162707  -0.1216394    1.2956094   0.5810063

Correlation and correlation matrix:

cor(iris$Sepal.Length, iris$Petal.Length)
## [1] 0.8717538
cor(iris[,1:4])
##              Sepal.Length Sepal.Width Petal.Length Petal.Width
## Sepal.Length    1.0000000  -0.1175698    0.8717538   0.8179411
## Sepal.Width    -0.1175698   1.0000000   -0.4284401  -0.3661259
## Petal.Length    0.8717538  -0.4284401    1.0000000   0.9628654
## Petal.Width     0.8179411  -0.3661259    0.9628654   1.0000000

Aggregate:

aggregate(Sepal.Length ~ Species, summary, data=iris)
##      Species Sepal.Length.Min. Sepal.Length.1st Qu. Sepal.Length.Median
## 1     setosa             4.300                4.800               5.000
## 2 versicolor             4.900                5.600               5.900
## 3  virginica             4.900                6.225               6.500
##   Sepal.Length.Mean Sepal.Length.3rd Qu. Sepal.Length.Max.
## 1             5.006                5.200             5.800
## 2             5.936                6.300             7.000
## 3             6.588                6.900             7.900
apply():
m <- matrix(C<-(1:10),nrow=5, ncol=5)
#Matrix:
m
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    6    1    6    1
## [2,]    2    7    2    7    2
## [3,]    3    8    3    8    3
## [4,]    4    9    4    9    4
## [5,]    5   10    5   10    5
#Apply()
apply(m, 2, sum)
## [1] 15 40 15 40 15
lapply():
names <- c("NAME1","NAME2","NAME3","NAME4")
names_lower <-lapply(names, tolower)
str(names_lower)
## List of 4
##  $ : chr "name1"
##  $ : chr "name2"
##  $ : chr "name3"
##  $ : chr "name4"
sapply():
#same as lapply but a vector is returned
smn <- sapply(iris$Sepal.Length, min)
smn
##   [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4 5.1
##  [19] 5.7 5.1 5.4 5.1 4.6 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8 5.4 5.2 5.5 4.9 5.0
##  [37] 5.5 4.9 4.4 5.1 5.0 4.5 4.4 5.0 5.1 4.8 5.1 4.6 5.3 5.0 7.0 6.4 6.9 5.5
##  [55] 6.5 5.7 6.3 4.9 6.6 5.2 5.0 5.9 6.0 6.1 5.6 6.7 5.6 5.8 6.2 5.6 5.9 6.1
##  [73] 6.3 6.1 6.4 6.6 6.8 6.7 6.0 5.7 5.5 5.5 5.8 6.0 5.4 6.0 6.7 6.3 5.6 5.5
##  [91] 5.5 6.1 5.8 5.0 5.6 5.7 5.7 6.2 5.1 5.7 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3
## [109] 6.7 7.2 6.5 6.4 6.8 5.7 5.8 6.4 6.5 7.7 7.7 6.0 6.9 5.6 7.7 6.3 6.7 7.2
## [127] 6.2 6.1 6.4 7.2 7.4 7.9 6.4 6.3 6.1 7.7 6.3 6.4 6.0 6.9 6.7 6.9 5.8 6.8
## [145] 6.7 6.7 6.3 6.5 6.2 5.9

Probability distribution

Binomial distribution:
dbinom(2, 3, 0.60)
## [1] 0.432
Poisson distribution:
dpois(2, 1)
## [1] 0.1839397
Normal probability distribution:
pnorm(150, 156, 4.6)
## [1] 0.09605751

Plots

Histogram:
hist(iris$Sepal.Length)

##### Density plot:

plot(density(iris$Sepal.Length))

##### Pie chart:

pie(table(iris$Species)) 

##### Barplot:

barplot(table(iris$Species))

##### Boxplot: Individual:

boxplot(iris$Sepal.Length)

Grouped:

boxplot(iris$Sepal.Length,iris$Sepal.Width)

boxplot(Sepal.Length~Species, data=iris)

##### Species-wise scatter plot:

with(iris, plot(Sepal.Length, Sepal.Width, col=Species, pch=as.numeric(Species)))

##### Pair plot:

pairs(iris)

3D plots:
# Import a library to view 3d plots
library("scatterplot3d")
## Warning: package 'scatterplot3d' was built under R version 4.0.2
scatterplot3d(iris$Petal.Width, iris$Sepal.Length, iris$Sepal.Width)

##### Heatmap

distMatrix <- as.matrix(dist(iris[,1:4]))
heatmap(distMatrix)

##### Contour plot:

filled.contour(volcano, color=terrain.colors, asp=1,plot.axes=contour(volcano, add=T))

##### Parallel coordinates:

parcoord(iris[1:4], col=iris$Species)

##### Parallel plots:

library(lattice)
parallelplot(~iris[1:4] | Species, data=iris)

Line plot:
plot(iris$Sepal.Length, iris$Sepal.Width, type="l") 

Panelling graphs:
par(mfrow=c(2,2))
hist(iris$Sepal.Length, main='Histogram',xlab='Sepal length', ylab ='Frequency', col=heat.colors(14))

boxplot(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length, iris$Petal.Width,  main='Iris boxplot of features', ylab='f',xlab='Shift', names = c('mm','mm','mm','mm'))

plot(iris$Sepal.Length,iris$Sepal.Width,main='Sepal length vs width', xlab='mm',ylab='mm',pch=2)
plot(iris$Petal.Length,iris$Sepal.Length,type="l",main='petal vs sepal length',xlab='mm',ylab='mm')
lines(iris$Petal.Length,iris$Sepal.Length,lty=2)


Loops, functions and conditionals

Functions, loops and conditionals:
# I made a palindrome checker to perform all three things mentioned above.

isplaindrome <- function(n){
    reverse = 0
    buff = n
    while (n > 0) {
      r = n %% 10
      reverse = reverse * 10 + r
      n = n %/% 10
    }
    if (reverse == buff)
    {
      print(paste("It is palindrome!", reverse))
    }
    else{
      print(paste("Not a palindrome", reverse))
    }
}

## Call the function:
isplaindrome(12345) # should return "Not a palindrome"
## [1] "Not a palindrome 54321"
isplaindrome(123321) # should return "It is palindrome!"
## [1] "It is palindrome! 123321"



NOTE: The clustering parts are not yet covered in class and will be presented in the later lab exercises